<template>
  <el-upload
    ref="upload"
    class="header-upload"
    :action="action"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :on-change="handleChange"
    :auto-upload="false"
    :http-request="uploadFile"
    name="file"
    :limit="1"
  >
    <el-button slot="trigger" :disabled="!!fileList.length" size="mini" type="primary">{{ selectLabel }}</el-button>
    <el-button style="margin-left: 10px;" :disabled="disabled" size="mini" type="success" @click="submitUpload">{{ uploadLable }}</el-button>
  </el-upload>
</template>

<script>
import axios from 'axios'
import { stringify } from 'qs'

async function upload(action, filename, file) {
  const param = new FormData()
  const configs = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
  param.append('name', file.name)
  param.append('nameRegular', file.name)
  param.append(filename, file)

  try {
    const response = await axios.post(action, param, configs)
    const data = response.data
    console.log('upload response:', data)
    if (response.status === 200 && data.code === 0) {
      return data.data
    }
    throw new Error(data.msg || '上传失败')
  } catch (error) {
    throw error
  }
}

export default {
  name: 'Upload',
  props: {
    selectLabel: {
      type: String,
      default: '选取文件'
    },
    uploadLable: {
      type: String,
      default: '上传'
    },
    action: {
      type: String,
      default: `${process.env.VUE_APP_BASE_API}/excel/model/file`
    },
    query: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      fileList: [],
      disabled: false
    }
  },
  computed: {
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log('handleRemove', file, fileList)
      this.disabled = false
      this.fileList = fileList
    },
    handlePreview(file) {
      console.log('handlePreview', file)
    },
    handleChange(file, fileList) {
      console.log('handleChange', file, fileList, this.$refs.upload)
      this.fileList = fileList
    },
    async uploadFile({ action, filename, file }) {
      try {
        this.disabled = true
        const query = stringify(this.query)
        const url = `${action}?${query}`
        const data = await upload(url, filename, file)
        this.$message.success('上传成功')
        this.$emit('on-succeed', data)
      } catch (error) {
        this.$message.error(error.message)
        console.error('上传错误:', error)
        this.$emit('on-fail', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-upload {
  display: inline-block;
  /deep/ .el-upload-list {
    display: inline-block;
  }
}
</style>
